package com.nbsaas.lbs.baidu.ip.service.impl;

import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.nbsaas.http.Connection;
import com.nbsaas.lbs.baidu.ip.request.IpRequest;
import com.nbsaas.lbs.baidu.ip.response.IpResponse;
import com.nbsaas.lbs.baidu.ip.service.IpService;
import com.nbsaas.lbs.baidu.v3.service.BaseService;
import com.nbsaas.lbs.baidu.v3.service.Config;
import com.nbsaas.utils.StringUtils;

public class IPServiceImpl extends BaseService implements IpService {
  
  
  public IPServiceImpl(Config config) {
    super(config);
  }
  @Override
  public IpResponse ip(IpRequest request) {
    IpResponse result = new IpResponse();
    Connection connection = getConnection("https://api.map.baidu.com/location/ip");
    if (request.getIp()!=null){
      connection.data("ip", request.getIp());
    }
    connection.data("coor", "bd09ll");
  
    
    connection.method(Connection.Method.GET);
    String body = execute(connection);
    if (StringUtils.isNotBlank(body)) {
      JsonParser parser = new JsonParser();
      JsonElement root = parser.parse(body);
      if (root == null) {
        return result;
      }
      result.setAddress(getString(root, "address"));
      result.setStatus(getString(root, "status"));
      JsonElement content = root.getAsJsonObject().get("content");
      if (content == null) {
        return result;
      }
      result.setSimpleAddress(getString(content, "address"));
      JsonElement detail = content.getAsJsonObject().get("address_detail");
      if (detail == null) {
        return result;
      }
      result.setCity(getString(detail, "city"));
      result.setCityCode(getString(detail, "city_code"));
      result.setDistrict(getString(detail, "district"));
      result.setProvince(getString(detail, "province"));
      result.setStreet(getString(detail, "street"));
      result.setStreetNumber(getString(detail, "street_number"));
      JsonElement point = content.getAsJsonObject().get("point");
      if (point == null) {
        return result;
      }
      result.setLongitude(point.getAsJsonObject().get("x").getAsFloat());
      result.setLatitude( point.getAsJsonObject().get("y").getAsFloat());
    }
    return result;
  }
  
  private String getString(JsonElement root, String key) {
    JsonElement element = root.getAsJsonObject().get(key);
    if (element != null) {
      return element.getAsString();
    } else {
      return "";
    }
  }
}
